package org.neowei.image.commond;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.neowei.common.exception.CommondException;

public class CommondContorl {
	private Process process;
	final public InputStream startCommond(String cmd) throws IOException {
		Runtime runtime = Runtime.getRuntime();
		InputStream inputStream = null;
		process = runtime.exec(cmd);
		inputStream = process.getErrorStream();
		return inputStream;
	}

	final public String getErrorResult(final InputStream inputStream)
			throws IOException {
		StringBuffer result = new StringBuffer();
		final InputStreamReader inputReader = new InputStreamReader(inputStream);
		final BufferedReader br = new BufferedReader(inputReader);
		String line = null;
		while ((line = br.readLine()) != null)
			result.append(line);
		new Thread(new closeStream(inputStream, inputReader, br)).start();
		new Thread(new closeProcess(process)).start();
		return result.toString();
	}

	private final class closeProcess implements Runnable {
		final Process process;

		public closeProcess(Process process) {
			this.process = process;
		}

		@Override
		public void run() {
			try {
				process.waitFor();
			} catch (InterruptedException e) {
				throw new CommondException("process waitfor error", e);
			}
			process.destroy();
		}
	}

	private final class closeStream implements Runnable {
		final InputStream inputStream;
		final InputStreamReader inputReader;
		final BufferedReader br;

		public closeStream(InputStream inputStream,
				InputStreamReader inputReader, BufferedReader br) {
			this.inputStream = inputStream;
			this.inputReader = inputReader;
			this.br = br;
		}

		@Override
		public void run() {
			try {
				inputStream.close();
				inputReader.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
